from rest_framework import serializers
import datetime, json

from activities.models import *
from merchants.models import *
from cashbonus.models import *
from businesses.models import *


class LuckyBagChildActivityModelSerializer(serializers.ModelSerializer):

    activity_type_str = serializers.CharField(source='get_activity_type_display', read_only=True)

    class Meta:
        model = LuckyBagChildActivity
        fields = ['id', 'banner', 'activity_type', 'activity_type_str']


class LuckyBagActivityModelSerializer(serializers.ModelSerializer):

    activity_time = serializers.SerializerMethodField(read_only=True)
    activity_set = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = LuckyBagActivity
        fields = ['id', 'activity_time', 'description', 'explain', 'activity_set']

    def get_activity_time(self, obj):
        return f'{obj.available_begin_time.strftime("%Y-%m-%d")}至{obj.available_end_time.strftime("%m-%d")}'

    def get_activity_set(self, obj):
        today = datetime.datetime.now()
        activity_set = LuckyBagChildActivity.objects.filter(parent_id=obj.id, available_end_time__gte=today, available_begin_time__lte=today).order_by('sort')
        return LuckyBagChildActivityModelSerializer(activity_set, many=True).data


class LuckyBagActivityModelSerializer1(serializers.ModelSerializer):

    activity_time = serializers.SerializerMethodField(read_only=True)
    activity_set = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = LuckyBagActivity
        fields = ['id', 'activity_time', 'description', 'explain', 'activity_set']

    def get_activity_time(self, obj):
        return f'{obj.available_begin_time.strftime("%Y-%m-%d")}至{obj.available_end_time.strftime("%m-%d")}'

    def get_activity_set(self, obj):
        today = datetime.datetime.now()
        activity_set = LuckyBagChildActivity.objects.filter(parent_id=obj.id).order_by('sort')
        return LuckyBagChildActivityModelSerializer(activity_set, many=True).data


class LuckyBagRecordListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    operate_type_str = serializers.CharField(source='get_operate_type_display', read_only=True)

    class Meta:
        model = LuckyBagRecord
        fields = ['id', 'create_time', 'operate_type', 'operate_type_str', 'lucky_bag', 'lucky_bag_balance']


class ScoutTheStoreLeaderboardModelSerializer(serializers.ModelSerializer):

    creator = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ScoutTheStoreLeaderboard
        fields = ('city', 'merhant_name', 'likes', 'creator')

    def get_creator(self, obj):
        try:
            return json.loads(obj.creator.replace("'", '"'))
        except:
            return ['-']